/**
 * 连接Java服务端的WS
 * 主要负责给Java服务端发消息
 */
const WebSocket = require("ws");
const sceneMap = require("../map/sceneMap");
const JAVA_SERVER = 'ws://192.168.66.111:8663'

class JavaClient {
  constructor(sceneId) {
    this.sceneId = sceneId;
    this.ws = null;
  }
  init(cb) {
    const url = `${JAVA_SERVER}/commentMessage/admin-${this.sceneId}`;
    this.ws = new WebSocket(url);
    this.ws.on("open", () => {
      console.log(`${this.sceneId}:Java WS connected`);
      if(cb) {
        cb();
      }
    });
    this.ws.on("close", () => {
      console.log(`${this.sceneId}:Java WS disconnected`);
      this.destroy();
    });
    this.ws.on("error", (err) => {
      console.log(`${this.sceneId}:Java WS error`, err);
      this.destroy();
    });
    sceneMap.addClient({
      sceneId: this.sceneId,
      javaClient: this,
    });
  }
  sendMsg(msg) {
    this.ws.send(JSON.stringify(msg));
  }
  destroy() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
    sceneMap.removeClient(this.sceneId);
  }
}

module.exports = JavaClient;
